console.log('[DouBao] content script loaded')

function click(selector) {
  return new Promise(async (resolve, reject) => {
    const el = document.querySelector(selector)

    if (!el) return reject(new Error(`找不到元素 ${selector}`))

    el.click()

    await sleep(500)

    resolve()
  })
}

// 延迟
function sleep(time) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve()
    }, time)
  })
}

async function locator(selector) {
  return await waitForSelector(selector)
}

async function chat(message) {
  console.log('[DouBao] 发送消息:', message)

  // 新对话
  await click('[data-testid="create_conversation_button"]')

  await waitForSelector('[data-testid="chat_input"]')

  const textarea = document.querySelector('[data-testid="chat_input"] textarea')
  if (!textarea) return console.error('找不到输入框')
  textarea.value = message
  textarea.dispatchEvent(new Event('input', { bubbles: true }))

  const sendBtn = document.querySelector('#flow-end-msg-send')
  if (!sendBtn) return console.error('找不到发送按钮')

  // 等待按钮可点击
  await new Promise(resolve => {
    const check = () => {
      if (sendBtn.getAttribute('aria-disabled') === 'false') {
        resolve()
      } else {
        setTimeout(check, 500)
      }
    }
    check()
  })

  sendBtn.click()
  console.log('[DouBao] 点击发送')
}

window.addEventListener('message', async event => {
  if (event.data.type === 'DOUBAO_SEND_MESSAGE') {
    const message = event.data.message

    await chat(message)

    // // 等待回答完成
    // await waitForAnswer()

    // // 获取结果
    // const result = await getResult()
    // console.log('[DouBao] 最终结果:', result)

    // // 把结果返回给 background.js
    // window.postMessage({ type: 'DOUBAO_RESULT', result }, '*')
  }
})

async function waitForAnswer() {
  console.log('[DouBao] 等待回答完成')

  await waitForSelector('[data-testid="audio_play_button"]')

  // 等待回答区出现
  // await waitForSelector('[data-testid="immersive_side_bar_chat"]')

  // 等待发送中按钮消失
  // await waitForSelector('[data-testid="chat_input_local_break_button"]', true)

  console.log('[DouBao] 回答完成')
}

async function waitForSelector(selector, hidden = false, timeout = 120_000) {
  console.log('waitForSelector')

  return new Promise((resolve, reject) => {
    const start = Date.now()

    const check = () => {
      const el = document.querySelector(selector)

      console.log('check', selector)

      if (hidden ? !el : el) {
        resolve(el)
      } else if (Date.now() - start > timeout) {
        reject(new Error(`waitForSelector 超时: ${selector}`))
      } else {
        setTimeout(check, 500)
      }
    }

    check()
  })
}

async function think() {
  const normal = document.querySelector('[data-testid="deep_think_select_button"]')
  const noNormal = document.querySelector('[data-testid="use-deep-thinking-switch-btn"]')

  if (normal) {
    const checked = normal.getAttribute('data-checked')
    return checked === 'true'
  } else if (noNormal) {
    const thinkBtn = noNormal.querySelector('button')
    const checked = thinkBtn?.getAttribute('data-checked')
    return checked === 'true'
  }
  return false
}

async function getResult() {
  const result = {}
  result.think = await think()

  if (result.think) {
    const collapseBlock = document.querySelectorAll('[data-testid="collapse_quota_block"]')
    if (collapseBlock.length > 0) {
      const lastCollapse = collapseBlock[collapseBlock.length - 1]
      const firstContent = lastCollapse.querySelector('[data-testid="message_text_content"]')
      if (firstContent) {
        result.thinkText = firstContent.textContent
        result.thinkHtml = firstContent.innerHTML
      }
    }
  }

  const msgList = document.querySelectorAll('[data-testid="message_text_content"]')
  if (msgList.length > 0) {
    const lastMsg = msgList[msgList.length - 1]
    result.contentText = lastMsg.textContent
    result.contentHtml = lastMsg.innerHTML
  }

  return result
}
